<template>
    <div class="user-info">
        <!-- 头像修改按钮 -->
        <div class="avatar-section">
            <el-avatar :size="100" :src="avatarUrl" @click="showAvatarDialog = true" />
        </div>

        <!-- 昵称修改按钮 -->
        <div class="nickname-section">
            <el-button @click="showNickNameDialog = true" type="text">
                {{ nickName }}
            </el-button>
        </div>

        <!-- 头像修改弹窗 -->
        <div v-if="showAvatarDialog" class="custom-dialog">
            <el-dialog v-model="showAvatarDialog" title="修改头像">
                <el-upload action="#" :show-file-list="false" :before-upload="handleAvatarUpload">
                </el-upload>
                <template #footer>
                    <span class="dialog-footer">
                    </span>
                </template>
            </el-dialog>
        </div>

        <div v-if="showNickNameDialog" class="custom-dialog">
            <el-dialog v-model="showNickNameDialog" title="修改昵称">
                <el-input v-model="newNickName" placeholder="请输入新昵称" />
                <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="handleNickNameChange">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>

        <div>
            <!-- 修改邮箱 -->
            <el-button @click="showEmailDialog = !showEmailDialog">{{ showEmailDialog ? '取消' : '修改邮箱' }}</el-button>
        </div>

        <div v-show="showEmailDialog" class="custom-dialog"
            style="display: flex; flex-direction: column; align-items: center; padding: 20px;">

            <el-form ref="formRef" :model="emailForm" :rules="emailRules">
                <el-form-item label="旧邮箱验证码" prop="oldEmailCode">
                    <el-input v-model="emailForm.oldEmailCode" placeholder="请输入旧邮箱验证码" />
                    <el-button @click="sendOldEmailCode" type="primary" size="small">发送验证码</el-button>
                </el-form-item>
                <el-form-item label="新邮箱" prop="newEmail">
                    <el-input v-model="emailForm.newEmail" placeholder="请输入新邮箱" />
                </el-form-item>
                <el-form-item label="新邮箱验证码" prop="newEmailCode">
                    <el-input v-model="emailForm.newEmailCode" placeholder="请输入新邮箱验证码" />
                    <!-- 通过 disabled 属性控制按钮是否可用 -->
                    <el-button @click="sendNewEmailCode" type="primary" size="small" :disabled="!oldEmailCodeSent">
                        发送验证码
                    </el-button>
                </el-form-item>
            </el-form>
            <el-button type="primary" @click="handleEmailChange">确定</el-button>
        </div>

        <div>
            <!-- 新增修改密码按钮 -->
            <el-button @click="showPasswordDialog = !showPasswordDialog">{{showPasswordDialog ? '取消' : '修改密码'}}</el-button>
        </div>

        <!-- 新增修改密码弹窗 -->
        <div v-show="showPasswordDialog" class="custom-dialog"
            style="display: flex; flex-direction: column; align-items: center; padding: 20px;">
            <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules">
                
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
                </el-form-item>
                <!-- 新增验证码输入项 -->
                <el-form-item label="验证码" prop="verificationCode">
                    <el-input v-model="passwordForm.verificationCode" placeholder="请输入验证码" />
                    <el-button @click="sendVerificationCode" type="primary" size="small" :disabled="isSendingCode || codeCountdown > 0">
                        {{ codeCountdown > 0 ? `${codeCountdown}s 后重试` : '发送验证码' }}
                    </el-button>
                </el-form-item>
            </el-form>
            <el-button type="primary" @click="handlePasswordChange">确定</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref , reactive } from 'vue';
import { ElAvatar, ElButton, ElDialog, ElInput, ElUpload, ElForm, ElFormItem, ElMessage } from 'element-plus';
import { UserStore } from '../store/user';
import require from '../require';
import axios from 'axios';

const userStore = UserStore();
// 初始化头像和昵称
const avatarUrl = ref('https://cube.elemecdn.com/6/94/4d3ea631b809e10b648a58dd57ba5jpeg.jpeg');
const nickName = ref('默认昵称');
nickName.value = userStore.userInfo.nickName;
avatarUrl.value = userStore.userInfo.avatarUrl;

// 控制弹窗显示
const showAvatarDialog = ref(false);
const showNickNameDialog = ref(false);
const newNickName = ref(nickName.value);
const showEmailDialog = ref(false);

// 记录旧邮箱验证码是否已发送
const oldEmailCodeSent = ref(false);

const passwordFormRef = ref(null);

// 邮箱表单数据
const emailForm = reactive({
    oldEmailCode: '',
    newEmail: '3495789702@qq.com',
    newEmailCode: ''
});

const formRef = ref(null);

const oldEmail = userStore.userInfo.email;

// 邮箱校验规则
const emailRules = ref({
    oldEmailCode: [
        { required: true, message: '请输入旧邮箱验证码', trigger: 'blur' }
    ],
    newEmail: [
        { required: true, message: '请输入新邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
    ],
    newEmailCode: [
        { required: true, message: '请输入新邮箱验证码', trigger: 'blur' }
    ]
});

// 处理头像上传
const handleAvatarUpload = async (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        avatarUrl.value = e.target.result;
        showAvatarDialog.value = false;
    };
    reader.readAsDataURL(file);
    const formData = new FormData();
    formData.append('image', file);
    const response = await axios.post('http://localhost:8080/zhongjianyu.cat.com/uploadImage', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });

    const res = await require.post('/user/setAvatar', {
        avatar: response.data.data.url
    });
    console.log(res);
    userStore.saveUser(res.user);
};

// 处理昵称修改
const handleNickNameChange = async () => {
    // 校验昵称是否为空
    if (!newNickName.value) {
        ElMessage.error('昵称不能为空');
        return;
    }
    // 这里可以添加保存昵称的逻辑，例如调用 API
    
    const res = await require.post('/user/setNickName', {
        nickName: newNickName.value
    });

    if (res.user) {
        userStore.saveUser(res.user);
        nickName.value = newNickName.value;
        showNickNameDialog.value = false;
        ElMessage.success('昵称修改成功');
    }
    console.log(res);
    
};

// 发送旧邮箱验证码
const sendOldEmailCode = async () => {
    try {
        // 这里需要替换为实际的发送验证码接口
        await require.get('/user/oldEmailCodeToChangeEmail');
        ElMessage.success('旧邮箱验证码发送成功');
        // 标记旧邮箱验证码已发送
        oldEmailCodeSent.value = true;
        console.log(oldEmailCodeSent);
    } catch (error) {
        ElMessage.error('旧邮箱验证码发送失败');
    }
};

// 发送新邮箱验证码
const sendNewEmailCode = async () => {
    try {
        // 使用内置的 type: 'email' 规则进行验证
        await formRef.value.validateField('newEmail');
    } catch (error) {
        ElMessage.error('请输入正确的新邮箱地址');
        return;
    }
    try {
        // 这里需要替换为实际的发送验证码接口
        await require.post('/user/newEmailCodeToChangeEmail', {
            email: emailForm.newEmail
        });
        ElMessage.success('新邮箱验证码发送成功');
    } catch (error) {
        ElMessage.error('新邮箱验证码发送失败');
    }
};

// 处理邮箱修改
const handleEmailChange = async () => {
    try {
        // 使用 formRef 来验证整个表单
        await formRef.value.validate();
    } catch (error) {
        ElMessage.error('请检查表单信息');
        return;
    }
    try {
        // 这里需要替换为实际的修改邮箱接口
        const res = await require.post('/user/changeEmail', {
            oldEmailCode: emailForm.oldEmailCode,
            email: emailForm.newEmail,
            newEmailCode: emailForm.newEmailCode
        });
        console.log(res);
        if ((res !== null) && (res === 200 || (typeof res !== 'number'))) {
            userStore.saveUser(res.user);
            showEmailDialog.value = false;
            ElMessage.success('邮箱修改成功');
        }
    } catch (error) {
        ElMessage.error('邮箱修改失败');
    }
};
// 控制修改密码弹窗显示
const showPasswordDialog = ref(false);

// 新增验证码相关状态
const isSendingCode = ref(false);
const codeCountdown = ref(0);

// 扩展密码表单数据
const passwordForm = reactive({
    newPassword: '',
    confirmPassword: '',
    verificationCode: '' // 新增验证码字段
});

// 扩展密码校验规则
const passwordRules = ref({
    
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        // 使用正则表达式验证密码
        { 
            pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]{6,16}$/, 
            message: '密码需包含字母和数字，长度为 6 到 16 位', 
            trigger: 'blur' 
        }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { 
            validator: (rule, value, callback) => {
                if (value !== passwordForm.newPassword) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            }, 
            trigger: 'blur' 
        }
    ],
    verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ]
});

// 发送验证码方法
const sendVerificationCode = async () => {
    isSendingCode.value = true;
    try {
        // 这里需要替换为实际的发送验证码接口
        await require.get('/user/sendPasswordChangeCode');
        ElMessage.success('验证码发送成功');
        codeCountdown.value = 60;
        const timer = setInterval(() => {
            if (codeCountdown.value > 0) {
                codeCountdown.value--;
            } else {
                clearInterval(timer);
            }
        }, 1000);
    } catch (error) {
        ElMessage.error('验证码发送失败');
    } finally {
        isSendingCode.value = false;
    }
};

// 修改处理密码修改方法，添加验证码参数
const handlePasswordChange = async () => {
    try {
        // 使用 passwordFormRef 来验证整个表单
        await passwordFormRef.value.validate();
    } catch (error) {
        ElMessage.error('请检查表单信息');
        return;
    }
    try {
        // 这里需要替换为实际的修改密码接口，添加验证码参数
        const res = await require.post('/user/changePassword', {
            newPassword: passwordForm.newPassword,
            code: passwordForm.verificationCode // 新增验证码参数
        });
        console.log(res);
        if ((res !== null) && (res === 200 || (typeof res !== 'number'))) {
            userStore.saveUser(res.user);
            showPasswordDialog.value = false;
            ElMessage.success('密码修改成功');
        } else {
            ElMessage.error(res.message || '密码修改失败');
        }
    } catch (error) {
        ElMessage.error('密码修改失败');
    }
};
</script>

<style scoped>
.user-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 20px;
    padding: 20px;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
}

.nickname-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    width: 200px;
}

.custom-dialog {
    border: 1px solid #dcdfe6; /* 添加边框 */
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1); /* 添加阴影 */
    border-radius: 8px; /* 添加圆角 */
}
</style>
